<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleAdd"
        >
          添加
        </el-button>
        <el-button
          icon="el-icon-delete"
          type="danger"
          @click="handleAnyDelete"
        >
          删除
        </el-button>
        <el-button
          v-if="false"
          v-popover:popoverAll
          type="primary"
          icon="el-icon-upload2"
        >
          导出Excel
        </el-button>
        <el-button
          v-if="false"
          v-popover:popoverPart
          type="primary"
          icon="el-icon-upload2"
        >
          导出选中行
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel>
        <el-cascader
          v-if="user.level <= 1"
          :options="townToVillage"
          :props="townToVillProp"
          placeholder="地区筛选"
          change-on-select
          clearable
          @change="townToVillageChange"
        />
        <el-select
          v-if="user.level == 2"
          v-model="queryForm.village"
          multiple
          placeholder="地区筛选"
          clearable
          @change="villageChange"
        >
          <el-option
            v-for="village in queryVillageAtt"
            :key="village.id"
            :label="village.name"
            :value="village.id"
          />
        </el-select>
        <el-form
          ref="form"
          :model="queryForm"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item>
            <el-input
              v-model="queryForm.keyword"
              placeholder="查询内容或字段"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              native-type="submit"
              @click="handleQuery"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="序号"
        width="95"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="village.name"
        label="所属村"
      />
      <el-table-column
        prop="name"
        label="资产类型名称"
        sortable="custom"
      />
      <el-table-column
        label="操作"
        width="180px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <table-edit
      ref="edit"
      @fetchData="fetchData"
    />

    <!-- 导出Excel -->
    <el-popover
      ref="popoverAll"
      placement="right"
      width="250"
      trigger="click"
    >
      <vab-query-form>
        <vab-query-form-left-panel :span="24">
          <el-form
            label-position="right"
            :inline="false"
            size="mini"
            @submit.native.prevent
          >
            <el-form-item label="文件名">
              <el-input
                v-model="filename"
                placeholder="请输出要导出文件的名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="文件类型">
              <el-select v-model="bookType">
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item"
                  :value="item"
                  clearable
                />
              </el-select>
            </el-form-item>
            <el-form-item label="自动列宽">
              <el-radio-group v-model="autoWidth">
                <el-radio :label="true">
                  是
                </el-radio>
                <el-radio :label="false">
                  否
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="allHandleDownload"
              >
                导出 Excel
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
      </vab-query-form>
    </el-popover>
    <!-- 导出选中行 -->
    <el-popover
      ref="popoverPart"
      placement="right"
      width="250"
      trigger="click"
    >
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form
            :inline="true"
            @submit.native.prevent
          >
            <el-form-item>
              <el-input
                v-model="filename"
                placeholder="请输出要导出文件的名称"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="partHandleDownload()"
              >
                导出选中行
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
      </vab-query-form>
    </el-popover>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
import TableEdit from "@/views/my-views/Capital/assets-type/TableEdit";
export default {
  name: "MyTable",
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  components: {
    TableEdit,
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      list: [],
      listLoading: false,
      layout: "total, sizes, prev, pager, next, jumper",
      total: 0,
      background: true,
      selectRows: "",
      elementLoadingText: "正在加载...",
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        town: "",
        village: "",
        keyword: "",
      },

      // excle 导出
      filename: "资产类型相关信息",
      autoWidth: true,
      bookType: "xlsx",
      options: ["xlsx", "csv", "txt"],

      table: {},
      selectedData: {},
      sort: [],

      // 搜索
      townToVillProp: {
        value: "id",
        label: "name",
        children: "village"
      },
      townToVillage: [],
      queryVillageAtt: [],
    };
  },
  created() {
    this.init()
    this.fetchData();
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    tableSortChange(column) {
      // const imageList = [];
      // this.$refs.tableSort.tableData.forEach((item, index) => {
      //   imageList.push(item.img);
      // });
      if(column.order) {
        this.sort = [`${column.prop},${column.order == 'descending' ? 'DESC': 'ASC'}`]
      } else {
        this.sort = []
      }
      this.fetchData()
    },
    setSelectRows(val) {
      this.selectRows = val;
    },
    handleAdd() {
      this.$refs["edit"].showEdit();
    },
    handleEdit(row) {
      this.$refs["edit"].showEdit(row);
    },
    handleDelete(id) {
      this.$baseConfirm("你确定要删除当前项吗", null, async () => {
        await this.delete(id);
      });
    },
    handleAnyDelete() {
      if (this.selectRows.length > 0) {
        const att = JSON.parse(JSON.stringify(this.selectRows));
        this.$baseConfirm("你确定要删除选中项吗", null, () => {
          att.forEach(async (item) => {
            await this.delete(item.id);
          });
        });
      } else {
        this.$baseMessage("未选中任何行", "error");
      }
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    getQuery() {
      let query  = JSON.parse(JSON.stringify(this.queryForm))
      //分页
      //limit page
      // fields=name,village&s={"name":{"$cont":"一个"}}&filter=village.town.id||$in||1&or=name||$cont||"也是"&or=&or=&sort=name,ASC&join=village.town&limit=2&offset=1&page=1
      //s={"$or": [{"isActive": false}, {"updatedAt": {"$notnull": true}}]}
      //镇村筛选
      let fields = ""
      let  s = {
        "$or": [
          {
            "name": {
              "$cont": query.keyword
            }
          },
          {
            "village.name": {
              "$cont": query.keyword
            }
          },
        ],
        init() {
          if(query.village) {
            if(Array.isArray(query.village) && query.village.length > 0) {
              this['village.id'] = {
                "$in": query.village 
              }
            } else if (!Array.isArray(query.village)) {
              this['village.id'] = {
                "$eq": query.village 
              }
            }
          }
          if(query.town) {
            this['village.town.id'] = {
              "$eq": query.town 
            }
          }
          return this
        }
      }
      console.log(query)
      let filterInfo = (query.village !== "" && query.village && (Array.isArray(query.village) ? query.village.length > 0 : true)) ? `filter=village.town.id||$eq||${query.town}&filter=village.id||$in||${query.village.toString()}`: 
                       ((query.town !== "" && query.town) ? `filter=village.town.id||$eq||${query.town}` : "")
      let or = ""
      let sort = `${this.sort.map(item => `sort=${item}`).join('&')}&sort=createdAt,DESC`
      let join = `join=village&join=village.town`
      let pageInfo = `limit=${query.pageSize}&page=${query.pageNo}`
      
      //列排序 列名 排序规则 ASC(递增),DESC(递降)
      //粗略搜索
      // let search = ''
      return `fields=${fields}&s=${JSON.stringify(s.init())}&${filterInfo}&or=${or}&${sort}&${join}&${pageInfo}`
    },
    async fetchData() {
      this.listLoading = true;
      let res = await this.$http.get("assets-type" + `?${this.getQuery()}`);
      this.list = res.data.data;
      this.total = res.data.total;
      this.listLoading = false;
      this.table = this.transformData(this.list)
      console.log(this.table)
    },
    
    async delete(id) {
      const check = await this.$http.get(`assets-type/${id}`)
      if(check.data['assets'] && (check.data['assets'].length > 0)) {
        this.$notify.error({
          title: '错误',
          message: `该财产类型下有财产${check.data['assets'].length}条, 请先删除该类型下的所有财产信息,再执行财产类型删除!`
        });
        return
      }
      const res = await this.$http.delete(`assets-type/${id}`);
      if (res.status == 200) {
        this.$baseMessage("删除成功", "success");
        this.fetchData()
      } else {
        this.$baseMessage("删除失败", "error");
      }
    },

    transformData(objectData) {
      let header = []
      let data = []
      if(objectData.length > 0) {
        for (const key in objectData[0]) {
           header.push(key)
        }
        objectData.forEach(item => {
          let att = []
          header.forEach( key => att.push(item[key]))
          data.push(att)
        })
      }
      return {
        header,
        data
      }
    },
    //excel 导出
    allHandleDownload() {
      import("@/vendor/ExportExcel").then((excel) => {
          const  { header, data }  =  this.table;
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
      });
    },
    partHandleDownload () {
      if(Array.isArray(this.selectedData.data) && this.selectedData.data.length > 0) {
        import("@/vendor/ExportExcel").then((excel) => {
          const { header, data }  =  this.selectedData;
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
        });
      } else {
        this.$baseMessage("请至少选择一行", "error");
      }
    },

    async init() {
      this.setQuery()
      if(this.user.level <= 1) {
        const res = await this.$http.get(`town?join=village`)
        this.townToVillage = res.data
      }else if(this.user.level == 2) {
        const res = await this.$http.get(`town/${this.user.town.id}?join=village`)
        this.queryVillageAtt = res.data.village
      }
    },
    setQuery() {
      if(this.user.level == 2) {
        this.queryForm.town = this.user.town.id
        console.log(this.queryForm.town)
      } else if (this.user.level == 3) {
        this.queryForm.town = this.user.town.id
        this.queryForm.village = this.user.village.id
      }
    },
    townToVillageChange(att) {
      this.queryForm.town = att[0]
      this.queryForm.village = att[1] || ""
      this.fetchData()
    },
    villageChange(att) {
      this.fetchData()
    },
  },
};
</script>
